package com.liuren.app

import android.content.Intent
import android.content.pm.PackageManager
import android.view.KeyEvent
import android.webkit.WebView
import android.widget.Toast

class MainActivity : TauriActivity() {
  private lateinit var wv: WebView

  override fun onWebViewCreate(webView: WebView) {
    wv = webView
  }

  private val keyEventMap = mapOf(
    KeyEvent.KEYCODE_BACK to "back",
    KeyEvent.KEYCODE_MENU to "menu",
    KeyEvent.KEYCODE_SEARCH to "search",
    KeyEvent.KEYCODE_VOLUME_DOWN to "volume_down",
    KeyEvent.KEYCODE_VOLUME_UP to "volume_up"
  )
  fun openQQMain() {
    try {
      // 1. 通过包名创建启动 Intent
      val intent = packageManager.getLaunchIntentForPackage("com.tencent.mobileqq")
        ?: throw Exception("QQ 未安装") // 若获取不到 Intent，说明未安装 QQ

      // 2. 启动 QQ（可添加 Flags 优化启动行为，如清空栈顶）
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // 在新任务栈启动，避免与当前应用栈混淆
      startActivity(intent)

    } catch (e: Exception) {
      // 3. 处理“未安装 QQ”的情况（引导用户去应用商店下载）
      Toast.makeText(this, "请先安装手机 QQ", Toast.LENGTH_SHORT).show()
    }
  }
  fun openWeChatMain() {
    try {
      // 1. 检查微信是否安装
      val packageName = "com.tencent.mm"
      val pm = packageManager
      val isInstalled = try {
        pm.getPackageInfo(packageName, 0)
        true
      } catch (e: PackageManager.NameNotFoundException) {
        false
      }

      if (!isInstalled) {
        Toast.makeText(this, "请先安装微信", Toast.LENGTH_SHORT).show()
      }  
      
      if(isInstalled){
        // 2. 创建启动微信的 Intent
        val intent = Intent()
        intent.action = Intent.ACTION_MAIN
        intent.addCategory(Intent.CATEGORY_LAUNCHER)
        intent.setClassName(packageName, "com.tencent.mm.ui.LauncherUI")
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        // 3. 启动微信
        startActivity(intent)
      }

    } catch (e: Exception) {
      Toast.makeText(this, "无法打开微信，请检查是否已安装", Toast.LENGTH_SHORT).show()
    }
  }

  override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    val jsCallbackName = keyEventMap[keyCode]
    val url = wv.url
    if (url != null) {
      if (url.endsWith("/")){
        super.onKeyDown(keyCode, event)
        return true
      }
    }
    if (url != null) {
      if (url.endsWith("qq")){
      openQQMain()
      }
    }
    if (url != null) {
      if (url.endsWith("weixin")){
     openWeChatMain()
      }
    }
    wv.evaluateJavascript(
      """
        try {
          window.__tauri_android_on_${if (jsCallbackName != null) "${jsCallbackName}_" else ""}key_down__(${if (jsCallbackName != null) "" else keyCode})
        } catch (_) {
          true
        }
    """.trimIndent()
    ) { result ->
      run {
        if (result != "false") {
          super.onKeyDown(keyCode, event)
        }
      }
    }
    return true
  }
}